//
//  UrbanLawEnforcementViewController.m
//  UrbanManagement
//
//  Created by Can on 18/4/11.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanLawEnforcementViewController.h"
#import "UrbanLawEnTextFild.h"
#import "UrbanLawEnTableViewCell.h"
#import "UrbanRegistCollectionView.h"
#import "UrbanBureauViewController.h"
#import "UrbanWhereViewController.h"
#import "UrbanPlatesNum.h"
#import "UrbanLawEnForEndViewController.h"
#import "PlateIDCameraViewController.h"


@interface UrbanLawEnforcementViewController ()<UITableViewDataSource,UITableViewDelegate,UrbanCollectionViewDelegate>
@property (nonatomic, strong) UrbanRegistCollectionView *collectView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIView *sectionView;
@property (nonatomic, strong) NSString *plateNumber;//车牌号
@property (nonatomic, strong) NSString *carType;//车辆类型
@property (nonatomic, strong) NSString *numPlateColor;//号牌颜色
@property (nonatomic, strong) NSIndexPath *lastIndex;

@end

@implementation UrbanLawEnforcementViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _carType = @"小车";
    
    _numPlateColor = @"蓝色";
    
    [self creatView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self initTitleWithTitle:@"开始执法"];
}

- (void)creatView{

    CGFloat height = NavBarHeight;
    
    _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 0)];
    _headView.backgroundColor = [UIColor whiteColor];
    
    [self creatCollectionView];
    
    _sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_collectView.frame), SCREENW, 0)];
    _sectionView.backgroundColor = [UIColor whiteColor];
    [_headView addSubview:_sectionView];
    
    
    [self creatHeadView];
    
    _headView.frame = CGRectMake(0, 0, SCREENW, CGRectGetMaxY(_sectionView.frame));
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 5*screenW_6, SCREENW, SCREENH - 45*screenW_6 - 20*screenW_6 - height) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    //提交
    UIButton *registBtn = [TomamaUI createButton:0 Frame:CGRectMake(15*screenW_6, SCREENH - 15*screenW_6 - 45*screenW_6 - height, SCREENW - 30*screenW_6, 45*screenW_6) targ:self sel:@selector(submit) titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:16*screenW_6] title:@"提交" image:nil backGroundImage:@"blue_button2"];
    registBtn.layer.cornerRadius = 3*screenW_6;
    registBtn.layer.masksToBounds = YES;
    [self.view addSubview:registBtn];
}

- (void)creatCollectionView
{
    //违章照片
    UILabel *passportPhoto = [TomamaUI createLabel:CGRectMake(15*screenW_6, 0, 85*screenW_6, 50*screenW_6) textAligment:0 font:[UIFont systemFontOfSize:15*screenW_6] textColor:Color(51, 51, 51) text:@"违章照片"];
    [_headView addSubview:passportPhoto];
    
    _collectView = [[UrbanRegistCollectionView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(passportPhoto.frame) + 20*screenW_6, 0, SCREENW - (CGRectGetMaxX(passportPhoto.frame) + 20*screenW_6), 100*screenW_6) number:2];
    _collectView.delegate = self;
    [_headView addSubview:_collectView];
}

- (void)creatHeadView
{
    __weak typeof(self) weakSelf = self;
    //车牌号
    UrbanPlatesNum *plateNum = [[UrbanPlatesNum alloc]initWithFrame:CGRectMake(15*screenW_6, 5*screenW_6, 0, 0) lableName:@"车牌号码" labelColor:nil text:_plateNumber placeholder:@"请输入车牌号" buttonTitle:@"" maxNum:8];
    [_sectionView addSubview:plateNum];
    plateNum.UrbanPlatesNumBlock = ^(NSString *plateNum){
        weakSelf.plateNumber = plateNum;
    };

    //车辆类型
    UrbanLawEnTextFild *carTypesTextFild = [[UrbanLawEnTextFild alloc]initWithFrame:CGRectMake(15*screenW_6, CGRectGetMaxY(plateNum.frame) + 5*screenW_6, 0, 0) lableName:@"车辆类型" labelColor:nil text:_carType placeholder:_carType buttonTitle:nil keyboardType:1 maxNum:0 type:UrbanLawEnTextFildColorType];
    [_sectionView addSubview:carTypesTextFild];
    [carTypesTextFild.btn addTarget:self action:@selector(choseCarTypes:) forControlEvents:UIControlEventTouchUpInside];
    
    //号牌颜色
    UrbanLawEnTextFild *plateColorTextFild = [[UrbanLawEnTextFild alloc]initWithFrame:CGRectMake(15*screenW_6, CGRectGetMaxY(carTypesTextFild.frame) + 5*screenW_6, 0, 0) lableName:@"号牌颜色" labelColor:nil text:_plateNumber placeholder:_numPlateColor buttonTitle:nil keyboardType:1 maxNum:0 type:UrbanLawEnTextFildColorType];
    [_sectionView addSubview:plateColorTextFild];
    [plateColorTextFild.btn addTarget:self action:@selector(numberPlateColor:) forControlEvents:UIControlEventTouchUpInside];
    
    //位子信息
    UrbanLawEnTextFild *whereTextFild = [[UrbanLawEnTextFild alloc]initWithFrame:CGRectMake(15*screenW_6, CGRectGetMaxY(plateColorTextFild.frame) + 5*screenW_6, 0, 0) lableName:@"违法位子" labelColor:nil text:_where placeholder:@"请输入地址" buttonTitle:@"地图选择" keyboardType:UIKeyboardTypeDefault maxNum:0 type:UrbanLawEnTextFildAddressType];
    [_sectionView addSubview:whereTextFild];
    [whereTextFild.btn addTarget:self action:@selector(mapBtn) forControlEvents:UIControlEventTouchUpInside];
    whereTextFild.UrbanLawEnTextFildBlock = ^(NSString *where){
        weakSelf.where = where;
    };
    
    //详细地址
    UrbanLawEnTextFild *addressTextFild = [[UrbanLawEnTextFild alloc]initWithFrame:CGRectMake(15*screenW_6, CGRectGetMaxY(whereTextFild.frame) + 5*screenW_6, 0, 0) lableName:@"详细地址" labelColor:nil text:_address placeholder:@"请输入详细地址" buttonTitle:nil keyboardType:UIKeyboardTypeDefault maxNum:0 type:UrbanLawEnTextFildWhereType];
    [_sectionView addSubview:addressTextFild];
    addressTextFild.UrbanLawEnTextFildBlock = ^(NSString *where){
        weakSelf.address = where;
    };
    
    _sectionView.frame = CGRectMake(0, CGRectGetMaxY(_collectView.frame), SCREENW, CGRectGetMaxY(addressTextFild.frame) + 19*screenW_6);
}

- (void)homeWhere:(NSInteger)num
{
    PlateIDCameraViewController *camera = [[PlateIDCameraViewController alloc] init];
    [self.navigationController pushViewController:camera animated:YES];
    
    camera.UrbanCameraBlock = ^(NSString *plateNumber, NSString *plateColor, UIImage *image) {
        
        CGFloat width = [TomamaUI getStringWeithtWith:[self currentDateStr] andHeigth:17 andFont:[UIFont systemFontOfSize:17]];
        //替换数据源
        [self.collectView.collectArray replaceObjectAtIndex:num withObject:[TomamaUI imageWithText:[self currentDateStr] textFont:17 textColor:[UIColor redColor] textFrame:CGRectMake(SCREENW - width - 20, SCREENH - 40, width, 20) originImage:image imageLocationViewFrame:CGRectMake(0, 0, SCREENW, SCREENH)]];
        //刷新数据
        [self.collectView.registCollectionView reloadData];
 
        if (plateNumber) {
            self.plateNumber = plateNumber;
            self.numPlateColor = [NSString stringWithFormat:@"%@色",plateColor];
            
            [self.sectionView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [self creatHeadView];
        }
    };
}

//获取当前时间
- (NSString *)currentDateStr{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];//设定时间格式,这里可以设置成自己需要的格式
    NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串
    return dateString;
}

- (void)choseCarTypes:(UIButton *)btn
{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *a1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [ac addAction:a1];
    
    for (int i = 0; i < CarTypes.count; i++) {
        UIAlertAction *a2 = [UIAlertAction actionWithTitle:CarTypes[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.carType = CarTypes[i];
            [btn setTitle:CarTypes[i] forState:UIControlStateNormal];
        }];
        [ac addAction:a2];
    }
    
    [self presentViewController:ac animated:YES completion:nil];
}

- (void)numberPlateColor:(UIButton *)btn
{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *a1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [ac addAction:a1];
    
    for (int i = 0; i < NumberPlateColor.count; i++) {
        UIAlertAction *a2 = [UIAlertAction actionWithTitle:NumberPlateColor[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.numPlateColor = NumberPlateColor[i];
            [btn setTitle:NumberPlateColor[i] forState:UIControlStateNormal];
        }];
        [ac addAction:a2];
    }
    
    
    [self presentViewController:ac animated:YES completion:nil];
}

- (void)mapBtn
{
    UrbanWhereViewController *where = [UrbanWhereViewController new];
    where.mapType = 1;
    [self.navigationController pushViewController:where animated:YES];
    where.UrbanWhereViewControllerBlock = ^(NSString *string, NSString *str, NSString *lat, NSString *lon){
        
        self.where = string;
        self.address = str;
        self.latitude = lat;
        self.longitude = lon;
        [self.sectionView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self creatHeadView];
    };
}

- (void)submit
{
    if (_plateNumber.length == 0) {
        
        [ToolViewVC addKeyAlterViewController:@"请输入车牌号" Controller:self];
        
    }else if (_address.length == 0){
        
        [ToolViewVC addKeyAlterViewController:@"请输入地址" Controller:self];
        
    }else if (_where.length == 0){
        
        [ToolViewVC addKeyAlterViewController:@"请输入详细地址" Controller:self];
        
    }else{
        BOOL imgType = NO;
        for (int i = 0; i<_collectView.collectArray.count; i++) {
            NSData *data1 = UIImagePNGRepresentation(_collectView.collectArray[i]);
            NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"add"]);
            if ([data isEqual:data1]) {
                imgType = YES;
            }
        }
        if (imgType) {
            [ToolViewVC addKeyAlterViewController:@"必须选择两张图片" Controller:self];
        }else{
            [self submitData];
        }
    }
}

- (void)submitData
{
    [HudHelper showProgressHudWithMessage:@"正在提交..." toView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableDictionary *dic = [NSMutableDictionary new];
        
        [dic setValue:self->_plateNumber forKey:@"carNumber"];
        [dic setValue:@"" forKey:@"carColour"];
        if ([self->_carType isEqualToString:@"小车"]) {
            [dic setValue:@"1" forKey:@"carType"];
        }else{
            [dic setValue:@"2" forKey:@"carType"];
        }
        [dic setValue:self->_numPlateColor forKey:@"carNumColour"];
        [dic setValue:self->_longitude forKey:@"longitude"];
        [dic setValue:self->_latitude forKey:@"latitude"];
        [dic setValue:self->_where forKey:@"carAddress"];
        [dic setValue:self->_address forKey:@"addressDetails"];
        [dic setValue:[Storage getToken] forKey:@"user.id"];
        [dic setValue:[self imageBase64:self->_collectView.collectArray[0]] forKey:@"image1"];
        [dic setValue:[self imageBase64:self->_collectView.collectArray[1]] forKey:@"image2"];
        [dic setValue:self->_flag forKey:@"orderState"];

        
        [HttpRequest PostrequestUrl:@"jeesite/appInterface/ZfOrderInfo/addRecord" Dic:dic completion:^(NSDictionary *responseDic)
         {
             NSLog(@"respon:%@",responseDic);
             if ([responseDic[@"success"] boolValue]) {//请求成功
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [HudHelper hideHudToView:self.view];
                     [standfault setObject:@"YES" forKey:@"lawen"];
                     [standfault synchronize];
                     UrbanLawEnForEndViewController *lawEndVC = [[UrbanLawEnForEndViewController alloc]init];
                     lawEndVC.orderNumber = [[responseDic objectForKey:@"result"] objectForKey:@"orderNumber"];
                     lawEndVC.plateNumber = self->_plateNumber;
                     lawEndVC.carType = self->_carType;
                     lawEndVC.numPlateColor = self->_numPlateColor;
                     lawEndVC.parkTime = [[responseDic objectForKey:@"result"] objectForKey:@"carParkTime"];
                     lawEndVC.address = [NSString stringWithFormat:@"%@%@",[[responseDic objectForKey:@"result"] objectForKey:@"carAddress"],[[responseDic objectForKey:@"result"] objectForKey:@"addressDetails"]];
                     lawEndVC.flag = self.flag;
                     [self.navigationController pushViewController:lawEndVC animated:YES];
                     
                 });
             }else//请求失败提示
             {
                 
             }
         }];
    });
}

- (NSString *)imageBase64:(UIImage *)image
{
    NSData *imagedata = UIImagePNGRepresentation(image);
    
    NSString *image64 = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    return image64;
}

//*************************************************************
#pragma mark - tabledelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return _headView.frame.size.height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return _headView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = @"HomeCell";
    UrbanLawEnTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UrbanLawEnTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 10*screenW_6 + 227/2*screenW_6;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当前cell row
    NSInteger newRow = [indexPath row];
    //记录上一次cell row
    NSInteger oldRow = (_lastIndex != nil) ? [_lastIndex row] : -1;
    if (newRow != oldRow)
    {
        //选中cell
        UrbanLawEnTableViewCell *newcell =  [tableView cellForRowAtIndexPath:indexPath];
        [newcell.choseBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
        //取消上一次选中cell
        UrbanLawEnTableViewCell *oldCell = [tableView cellForRowAtIndexPath:_lastIndex];
        [oldCell.choseBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    }
    _lastIndex = indexPath;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
